package orm

import (
	"errors"

	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/core"
	"github.com/go-xorm/xorm"
	_ "github.com/yingshengtech/go-mssqldb"
	"yingsheng.com/go-api-server/config"
	//_ "github.com/mattn/go-sqlite3"
)

var Engineer *Engine

type Engine struct {
	xormEngine map[string]*xorm.Engine
}

func NewEngine() (*Engine, error) {
	Engineer = &Engine{
		xormEngine: make(map[string]*xorm.Engine),
	}

	var err error
	var driverName, dataSourceName string
	var xormEngine *xorm.Engine

	for _, db := range config.Configer.DbConf {
		driverName, dataSourceName, err = getConnect(db)
		if err != nil {
			break
		}

		xormEngine, err = xorm.NewEngine(driverName, dataSourceName)
		if err != nil {
			break
		}

		if err = xormEngine.Ping(); err != nil {
			break
		}

		// 连接池的空闲数大小
		//xormEngine.SetMaxIdleConns(5)
		// 最大打开连接数
		//xormEngine.SetMaxConns(500)

		//结构体命名与数据库一致
		xormEngine.SetMapper(core.NewCacheMapper(new(core.SameMapper)))

		Engineer.xormEngine[db.Alias] = xormEngine
	}

	return Engineer, err
}

//获取数据库引擎
func (e *Engine) Get(mi ModelInterface) (*xorm.Engine, error) {
	alias := mi.DatabaseAlias()
	engine, ok := e.xormEngine[alias]
	if !ok {
		return nil, errors.New("数据库引擎：" + alias + "不存在")
	}

	return engine, nil
}

// 获取数据库连接信息
func getConnect(db config.DbConfig) (string, string, error) {
	var err error
	driverName := ""
	dataSourceName := ""
	switch db.Type {
	case "mssql":
		driverName = "mssql"
		dataSourceName += "server=" + db.Server
		dataSourceName += ";port=" + db.Port
		dataSourceName += ";database=" + db.Name
		dataSourceName += ";user id=" + db.User
		dataSourceName += ";password=" + db.Password
		//	case "odbc":
		//		//lunny mssql driver
		//		driverName = "odbc"
		//		dataSourceName = "driver={SQL Server}"
		//		dataSourceName += ";Server=" + db["server"] + "," + db["port"]
		//		dataSourceName += ";Database=" + db["database"]
		//		dataSourceName += ";uid=" + db["user"] + ";pwd=" + db["password"] + ";"
	case "mysql":
		driverName = "mysql"
		dataSourceName = db.User + ":" + db.Password
		dataSourceName += "@(" + db.Server + ":" + db.Port + ")/"
		dataSourceName += db.Name + "?charset=utf8&loc=Asia%2FShanghai"
	case "sqlite3":
		driverName = "sqlite3"
		dataSourceName = db.Name
	default:
		err = errors.New("不支持的数据库类型：" + db.Type)
	}

	return driverName, dataSourceName, err
}
